package com.wzg.cs3_print_test

import androidx.annotation.NonNull
//
//import io.flutter.embedding.engine.plugins.FlutterPlugin
//import io.flutter.plugin.common.MethodCall
//import io.flutter.plugin.common.MethodChannel
//import io.flutter.plugin.common.MethodChannel.MethodCallHandler
//import io.flutter.plugin.common.MethodChannel.Result
import android.app.Activity
import android.graphics.Bitmap
import com.example.flutter_plugin.printer_cs3.BlePrintManager
import com.example.flutter_plugin.printer_cs3.PrintListener
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File

/** Cs3PrintTestPlugin */
class Cs3PrintTestPlugin : FlutterPlugin, MethodCallHandler, ActivityAware {

    private lateinit var channel: MethodChannel
    private var activity: Activity? = null

    /**
     * FlutterPlugin
     */
    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_plugin")
        channel.setMethodCallHandler(this)
    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }


    /**
     * MethodChannel
     */
    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {

            //获取Android系统版本号
            "getPlatformVersion" -> {
                result.success("Android ${android.os.Build.VERSION.RELEASE}")
            }
            //cs3 打印pdf的byte[]
            "print_cs3_pdf" -> {
                //拿到对应的数据
                //将数据转换为pdf文件
                //将pdf转换bitmaps
                val map: Map<String, Object> = call.arguments as Map<String, Object>
                val bytes = map["byte"] as ByteArray
                val file: File = Utils.getFile(bytes, "test.pdf")
                val bitmaps = Utils.pdfToBitmap(activity, file)
                activity?.applicationContext?.let {
                    BlePrintManager.printZicoxCS3(it, map["address"].toString(), bitmaps, 1)
                }
            }
            else -> {

            }
        }

    }


    /**
     * ActivityAware
     */
    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
        this.onDetachedFromActivity()
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        this.onAttachedToActivity(binding)
    }

    override fun onDetachedFromActivity() {
        activity = null
    }


}
